#pragma once

#include <unordered_map>
#include <iostream>
#include <fstream>
#include "Common.hpp"

static const std::string sep = ":";

class Dict
{
private:
    void Dict_init()
    {
        // open profiles 
        std::fstream in(_path);
        if(!in.is_open())
        {
            perror("is_open");
            exit(FSTREAM_ERROR);
        }

        // open success
        std::string info;
        while(std::getline(in, info))
        {
            // 定位
            size_t pos = info.find(sep);
            if(pos == std::string::npos) continue; // empty line
            
            // 分割
            std::string key = info.substr(0, pos);
            if(key.empty()) continue; // not complete
            std::string value = info.substr(pos+sep.size());
            if(value.empty()) continue; // not complete

            // 插入
            _dict.insert(std::make_pair(key,value));

        }
        in.close();
    }

public:
    Dict(std::string path = "./dict.txt")
        :_path(path)
    {
        Dict_init();
    }

    std::string Translate(const std::string& word)
    {
        auto iter = _dict.find(word);
        if(iter == _dict.end()) return "Not exist";
        return iter->second;
    }

private:
    std::unordered_map<std::string, std::string> _dict;
    std::string _path;

};